package com.group5.controller;
import com.group5.dao.GroupAndCustomerMapper;
import com.group5.dao.GroupsAndEmployeesMapper;
import com.group5.dao.PlatformMapper;
import com.group5.dao.UserssMapper;
import com.group5.pojo.GroupAndCustomer;
import com.group5.pojo.GroupsAndEmployees;
import com.group5.pojo.Platform;
import com.group5.pojo.Userss;
import com.group5.service.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.util.List;

/**
 * author:郝文韬
 * 本文件已经不含boolean返回类型的方法
 */

@RestController
@RequestMapping("/seller")
public class SellerController {
    @Autowired
    UserssMapper userssMapper;
    BuyerService buyerService=new BuyerService();
    SellerService sellerService=new SellerService();
    UserssService userssService = new UserssService();
    BooleanToJsonService booleanToJsonService=new BooleanToJsonService();
    AdminService adminService = new AdminService();
    @Autowired
    GroupsAndEmployeesMapper groupsAndEmployeesMapper;
    @Autowired
    GroupAndCustomerMapper groupAndCustomerMapper;
    @Autowired
    PlatformMapper platformMapper;


    @GetMapping("/getPlatformByUsername")
    public Platform getPlatformByUsername(@RequestParam String username){
        List<Userss> listUser= userssMapper.selectByExample(userssService.getUserInfoByUsernameService(username));
        if(listUser.isEmpty()){
            System.out.println("用户名不存在!");
            return null;
        }
        return platformMapper.selectByPrimaryKey(listUser.get(0).getOid());
    }

    /**
     * 给出一个用户名,返回它的所有信息
     * @param user_name
     * @return 对应的Userss的一个实体
     */
    @GetMapping("/getUserInfoByUser_name")
    public Userss getUserInfoByUser_name(@RequestParam String user_name){
        List<Userss> list = userssMapper.selectByExample(userssService.getUserInfoByUsernameService(user_name));
        if(list.isEmpty()){
            return null;
        }
        for(Userss userss:list){
            userss.setAnswer(null);
        }
        return list.get(0);
    }
    /**
     * 给出一个用户名,返回它的所有信息
     * @param username
     * @return 对应的Userss的一个实体
     */
    @GetMapping("/getUserInfoByUsername")
    public Userss getUserInfoByUsername(@RequestParam String username){
        List<Userss> list = userssMapper.selectByExample(userssService.getUserInfoByUsernameService(username));
        if(list.isEmpty()){
            return null;
        }
        for(Userss userss:list){
            userss.setAnswer(null);
        }
        return list.get(0);
    }
    /**
     * 获得一个oid对应的所有的用户信息
     * @param oid
     * @return List<Userss>
     */
    @GetMapping("/getEmployeesBySellerOid")
    public List<Userss> getEmployeesByOid(@RequestParam int oid){
        List<Userss> list = userssMapper.selectByExample(buyerService.getEmployeesBySellerOid(oid));
        for(Userss userss:list){
            userss.setAnswer(null);
        }
        return list;
    }
    /**
     * 获得一个用户名对应的用户信息
     */
    @GetMapping("/getUserInfoByUserName")
    public Userss getUserInfoByUserName(@RequestParam String username){
       // System.out.println(username);
        List<Userss> userssList= userssMapper.selectByExample(userssService.getUserInfoByUsernameService(username));
        if(userssList.size()!=1){
            System.out.println(" getUserInfoByUserName方法查询有误\n");
        }
        return userssList.get(0);
    }
    /**
     * 提供一个uid,获得他的所有信息
     * @param uid
     * @return Userss
     */
    @GetMapping("getUserinfo")
    public Userss getUserinfo(@RequestParam int uid){
        Userss userss=userssMapper.selectByPrimaryKey(uid);
        if(userss!=null){
            userss.setAnswer(null);
        }
        return userss;
    }
    /**
     * 提供一个卖方用户uid,返回用户有没有分组
     * 主要作用是看这个是不是空,以判断员工有没有在组里
     * @param uid
     * @return boolean
     */
    @GetMapping("isEmployeeGrouped")
    public BooleanToJsonService getUserssGroup(@RequestParam int uid){
        booleanToJsonService.setCheck(!groupsAndEmployeesMapper.selectByExample(buyerService.getEmployeesAndGroupByUid((uid))).isEmpty());
        return booleanToJsonService;
    }

    /**
     *
     *提供一个卖方管理员用户名,返回他所有的组号,不重复
     *      * @param username
     *      * @return List<Integer>
     */
    @GetMapping("/getAllGroupsByUsername")
    public List<Integer> getAllGroupsByUsername(@RequestParam String username){
        List<Userss> list = userssMapper.selectByExample(userssService.getUserInfoByUsernameService(username));
        if(list.isEmpty()){
            return null;
        }
        return groupsAndEmployeesMapper.getAllGroupsBySellerOid(list.get(0).getOid());
//        List<GroupListString> groupListStrings= new ArrayList<>();
//        List<Integer> list = groupsAndEmployeesMapper.getAllGroupsBySellerOid(oid);
//        for(Integer ele : list){
//            groupListStrings.add(new GroupListString(ele));
//        }
//        return groupListStrings;
    }

    /**
     * 创建新的组
     * 这里前端要把写入数据库的东西都弄好
     *      这个人的uid,oid,组号,区域,employee_states可以是空所以不写了
     *      组号重复则返回false
     *      返回类型为boolean
     * @param
     * @return booleanToJsonService
     */
    @PostMapping("createNewGroup")
    public BooleanToJsonService createNewGroup(@RequestBody GroupsAndEmployees groupsAndEmployees){

        groupsAndEmployees.setIs_group_leader(true);
        if(!groupsAndEmployeesMapper.selectByExample(sellerService.selectGroupByGroupnumberAndOid(groupsAndEmployees.getGroup_number(), groupsAndEmployees.getOid())).isEmpty()) {
            System.out.println("组已经存在,添加失败\n");
            booleanToJsonService.setCheck(false);//组已经存在了,最终返回false
            return booleanToJsonService;
        }
        booleanToJsonService.setCheck(1==groupsAndEmployeesMapper.insertSelective(groupsAndEmployees));
        return booleanToJsonService;
    }

    /**
     * 将已有的未分组的员工分到已有的组
     *      这里前端要把写入数据库的东西都弄好,除了区域,因为区域前端没拿到.
     *      后端会自动根据组号找到组的区域.
     *      即3个信息:uid,oid,组号
     * @param groupsAndEmployees
     * @return boolean
     */
    @PostMapping("addEmpIntoGroup")
    public BooleanToJsonService addEmpIntoGroup(@RequestBody GroupsAndEmployees groupsAndEmployees){
        int uid=groupsAndEmployees.getUid();
        List<GroupsAndEmployees>list = groupsAndEmployeesMapper.
                selectByExample(sellerService.
                        addEmpIntoGroupService(groupsAndEmployees.
                                getGroup_number(),groupsAndEmployees.getOid()));

        if(list.isEmpty()){//没查到组,加入失败
            booleanToJsonService.setCheck(false);
            return booleanToJsonService;
        }
        groupsAndEmployees.setArea(list.get(0).getArea());
        groupsAndEmployees.setIs_group_leader(false);
        booleanToJsonService.setCheck(1==groupsAndEmployeesMapper.insertSelective(groupsAndEmployees));
        return booleanToJsonService;
    }

    /**
     * 根据前端传过来的uname在user表中查找对应的oid
     * 根据买方oid，以及前端传回卖方oid，以及“通过”or不通过“不通过”字符串
     * 卖方读取自己oid对应的状态为3的申请，字符串为“不通过”，则将状态改为2，返回空
     *                                     字符串为“通过”，则将状态改为1，同时根据自己的oid查找自己所有的组号，返回组号列表给前端
     * @param uname
     * @param sid
     * @param s
     * @return

     */
    @GetMapping("/checkbuyer")
    public List<Integer> checkBuyerQualification(@RequestParam String uname, @RequestParam int sid, @RequestParam String s){
        int bid = userssMapper.getBuyerOidByUsername(uname);
        List<GroupAndCustomer> groupAndCustomers = groupAndCustomerMapper.selectByExample(buyerService.selectByBuyerAndSellerOid(bid,sid));
        if(!groupAndCustomers.isEmpty()){
            if(groupAndCustomers.get(0).getBuyer_application_status()==3&&s.equals("通过")){
                groupAndCustomers.get(0).setBuyer_application_status(1);
                groupAndCustomerMapper.updateByPrimaryKeySelective(groupAndCustomers.get(0));
                return groupsAndEmployeesMapper.getAllGroupsBySellerOid(sid);
            }
            else if(groupAndCustomers.get(0).getBuyer_application_status()==3&&s.equals("不通过")){
                groupAndCustomers.get(0).setBuyer_application_status(2);
                groupAndCustomerMapper.updateByPrimaryKeySelective(groupAndCustomers.get(0));
                return null;
            }
            else
                return null;
        }
        else
            return null;
    }

    /**
     * 前端传回一个组号，一个卖方oid，一个买方name，根据前端传过来的uname在user表中查找对应的oid
     * 更新表，返回true
     * @param uname
     * @param sid
     * @param gid
     * @return
     */
    @GetMapping("/distributegroup")
    public BooleanToJsonService distributeGroupNumbers(@RequestParam String uname,@RequestParam int sid,@RequestParam int gid){
        int bid = userssMapper.getBuyerOidByUsername(uname);

        List<GroupAndCustomer> groupAndCustomers = groupAndCustomerMapper.selectByExample(buyerService.selectByBuyerAndSellerOid(bid,sid));
        groupAndCustomers.get(0).setGroup_number(gid);
        groupAndCustomerMapper.updateByPrimaryKeySelective(groupAndCustomers.get(0));
        booleanToJsonService.setCheck(true);
        return booleanToJsonService;
    }


    /**
     * 卖方管理员审核买方申请，卖方管理员同意该申请。
     * 此时需要将买方分组，前端选取组号，向后端传参数：卖方管理员的username，买方机构的oid，组号groupnumber。
     *      根据传入的参数，获取group_and_customer表项中的group_number、buyer_oid、seller_oid，从数据库找出这一行（buyer_oid与seller_oid是主键）
     *      然后更新该行的buyer_application_status为1，group_number为参数groupnumber。
     * @param username 卖方管理员用户名，用于查找卖方机构
     * @param oid 买方机构oid
     * @param group_number 分组的组号
     * @return
     */
    @PutMapping("/groupbuyer")
    public int GroupBuyer(@RequestParam String username,@RequestParam int oid,@RequestParam int group_number){
        Userss SellerAdmin=userssMapper.selectByExample(sellerService.selectUserByUsernameExample(username)).get(0);
        Platform Seller=platformMapper.selectByPrimaryKey(SellerAdmin.getOid());
        GroupAndCustomer groupAndCustomer=groupAndCustomerMapper.selectByPrimaryKey(oid,Seller.getOid());
        groupAndCustomer.setBuyer_application_status(1);
        groupAndCustomer.setGroup_number(group_number);
        return groupAndCustomerMapper.updateByPrimaryKey(groupAndCustomer);
    }

    /**
     * 卖方管理员审核买方申请，卖方管理员拒绝申请。
     * 前端传参数卖方管理员的username，买方机构的oid。
     * 根据传入的参数，获取group_and_customer表项中的buyer_oid、seller_oid，从数据库找出这一行（buyer_oid与seller_oid是主键）
     * 然后更新该行的buyer_application_status为2
     * @param username
     * @param oid
     * @return
     */
    @PutMapping("/SellerRefusedBuyerApplication")
    public int SellerRefusedBuyerApplication(@RequestParam String username,@RequestParam int oid){
        Userss SellerAdmin=userssMapper.selectByExample(sellerService.selectUserByUsernameExample(username)).get(0);
        Platform Seller=platformMapper.selectByPrimaryKey(SellerAdmin.getOid());
        GroupAndCustomer groupAndCustomer=groupAndCustomerMapper.selectByPrimaryKey(oid,Seller.getOid());
        groupAndCustomer.setBuyer_application_status(2);
        return groupAndCustomerMapper.updateByPrimaryKey(groupAndCustomer);
    }

    /**
     * 从一个卖方机构移除一个员工,提供uid
     * 试图删除组长和管理员都会删除失败
     * @param uid
     * @return 包装好的 boolean 成功为true
     */
    @PostMapping("/removeEmployeeByUid")
    public BooleanToJsonService removeEmployeeByUid(@RequestParam int uid){

        Userss userss = userssMapper.selectByPrimaryKey(uid);
        if(2==userss.getUser_authority()){      //这个人是管理员,删除失败
            booleanToJsonService.setCheck(false);
            return booleanToJsonService;
        }
        List<GroupsAndEmployees> list =groupsAndEmployeesMapper.selectByExample(sellerService.uidAndGroupLeaderService(uid));
        if(!list.isEmpty()) {       //这个人是组长,删除失败
            booleanToJsonService.setCheck(false);
            System.out.println("删除组长失败");
            return booleanToJsonService;
        }

        //将员工的oid信息移除
        Userss userss1=userssMapper.selectByPrimaryKey(uid);
        userss1.setOid(null);
        userss1.setUser_authority(1);
        userss1.setIs_organization_accept(0);
        boolean b1 =  1==userssMapper.updateByPrimaryKey(userss1);

        //将员工与组的信息移除
        boolean b2 = true;
        List<GroupsAndEmployees> groupsAndEmployeesList=groupsAndEmployeesMapper.selectByExample(sellerService.getUserAndGroupInfoByUidService(uid));
        if(! groupsAndEmployeesList.isEmpty()){//员工在组里才删除
            b2 = 1==groupsAndEmployeesMapper.deleteByExample(sellerService.getUserAndGroupInfoByUidService(uid));
            System.out.println("删除成功");
        }

        booleanToJsonService.setCheck(b1&&b2);
        return booleanToJsonService;
    }

    /**
     * seller wants to know who is applying to be his buyer
     * frontend give admin's username
     * backend give a list of platforms who is applying.
     * @param username
     * @return
     */
    @GetMapping("/sellerQueryApplyingBuyers")
    public List<Platform> sellerQueryApplyingBuyers(@RequestParam String username){
        List<Userss> list = userssMapper.selectByExample(userssService.getUserInfoByUsernameService(username));
        if(list.isEmpty()){
            return null;
        }
        return platformMapper.selectApplyingBuyer(list.get(0).getOid());
    }
    /**
     * 静态内部类,暂时没什么用,万一要用到就不删了
     */
    public static class GroupListString {
        Integer group_number;
        GroupListString(Integer group_number){
            this.group_number=group_number;
        }
        GroupListString() {
        }
        public Integer getAuthority() {
            return group_number;
        }
    }

}
